package networking;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import interfaces.menu.joinGame.gamesTable.GamesTableWidget;

public class GameInfoCreator {
	
	public static final int REQUEST = 42;
	public static final int TIMEOUT = 100;
	
	public GameInfoCreator() {}
	
	public GamesTableWidget createWidget(String ip) {
		Socket socket = null;
		ObjectInputStream ois = null;
		ObjectOutputStream oos = null;
		
		try {
			socket = new Socket();
			long startTime = System.currentTimeMillis();
			socket.connect(new InetSocketAddress(ip, ServerInfoThread.INFO_PORT), TIMEOUT);
			int ping = (int)(System.currentTimeMillis() - startTime);
			
			oos = new ObjectOutputStream(socket.getOutputStream());
			
			oos.writeInt(REQUEST);
			oos.flush();
			
			ois = new ObjectInputStream(socket.getInputStream());
			
			Object obj = ois.readObject();
			
			if(obj instanceof GamesTableWidget) {
				GamesTableWidget w = (GamesTableWidget)obj;
				w.setPing(ping);
				return w;
			}
			return null;
		} catch(Exception e) {
		} finally {
			if(ois != null) {
				try { ois.close(); }
				catch(Exception e) { e.printStackTrace(); }
			}
			if(oos != null) {
				try { oos.close(); }
				catch(Exception e) { e.printStackTrace(); }
			}
			if(socket != null) {
				try { socket.close(); }
				catch(Exception e) { e.printStackTrace(); }
			}
		}
		return null;
	}
}